﻿namespace WMS6.BLL
{
    using System;
    using System.Collections.Generic;
    using System.Data.Common;
    using System.IO;
    using System.ServiceModel;
    using System.ServiceModel.Channels;
    using System.Text;
    using System.Xml;
    using WMS6.Common;
    using WMS6.DALFactory;
    using WMS6.DataEntity;
    using WMS6.DBUtility;
    using WMS6.IDAL;

    public class CEABLL
    {
        private static readonly ICommonMethodDA commonMethod = DataAccess.CreateCommonMethod();
        private static readonly ICustomerDA customerDA = DataAccess.CreateCustomerDA();
        private List<string> dataBaseID;
        private static readonly IEdiLogDA edilogDA = DataAccess.CreateEdiLogDA();
        private static readonly IIntransitDA IntransitDA = DataAccess.CreateIntransitDA();
        private static readonly IIntransitDetailDA IntransitDetailDA = DataAccess.CreateIntransitDetailDA();
        private static readonly IOrderDetailDA orderDetailDA = DataAccess.CreateOrderDetailDA();
        private static readonly IOrdersDA ordersDA = DataAccess.CreateOrdersDA();
        private static readonly IOwnerDA ownerDA = DataAccess.CreateOwnerDA();
        private static readonly IPackDA packDA = DataAccess.CreatePackDA();
        private static readonly IPickDetailDA pickDetailDA = DataAccess.CreatePickDetailDA();
        private PubParasInfo pubParasInfo;
        private static readonly IReceiptDA receiptDA = DataAccess.CreateReceiptDA();
        private static readonly IReceiptDetailDA receiptDetailDA = DataAccess.CreateReceiptDetailDA();
        private static readonly IReceiptDetailLpnDA receiptDetailLpnDA = DataAccess.CreateReceiptDetailLpnDA();
        private static readonly ISkuDA skuDA = DataAccess.CreateSkuDA();
        private string strCurrentWhName;
        private string strUrl;
        private static readonly ISysSettingDA sysSettingDA = DataAccess.CreateSysSettingDA();

        public CEABLL()
        {
            this.pubParasInfo = null;
            this.strCurrentWhName = string.Empty;
            this.strUrl = string.Empty;
        }

        public CEABLL(string currentWH)
        {
            this.pubParasInfo = null;
            this.strCurrentWhName = string.Empty;
            this.strUrl = string.Empty;
            this.strCurrentWhName = currentWH;
            if (!string.IsNullOrEmpty(currentWH))
            {
                this.dataBaseID = commonMethod.GetDataBaseID(currentWH);
                if (this.dataBaseID == null)
                {
                    PublicMethod.GetInstance().ShowAlertMessage("C001");
                }
            }
            else
            {
                PublicMethod.GetInstance().ShowAlertMessage("C002");
            }
        }

        public CEABLL(PubParasInfo tempPubParasInfo)
        {
            this.pubParasInfo = null;
            this.strCurrentWhName = string.Empty;
            this.strUrl = string.Empty;
            if (!string.IsNullOrEmpty(tempPubParasInfo.CurrentWH))
            {
                this.dataBaseID = commonMethod.GetDataBaseID(tempPubParasInfo.CurrentWH);
                if (this.dataBaseID == null)
                {
                    PublicMethod.GetInstance().ShowAlertMessage("C001", this.pubParasInfo.UserLanguage);
                }
                else
                {
                    this.pubParasInfo = new PubParasInfo();
                    this.pubParasInfo = tempPubParasInfo;
                }
            }
            else
            {
                PublicMethod.GetInstance().ShowAlertMessage("C002", this.pubParasInfo.UserLanguage);
            }
        }

        public string CheckSAPValidation(string recepitID)
        {
            string result = string.Empty;
            try
            {
                ReceiptInfo receiptInfo = receiptDA.GetReceiptByID(recepitID, this.dataBaseID[0], this.pubParasInfo);
                if ((receiptInfo != null) && !string.IsNullOrEmpty(receiptInfo.ReceiptID))
                {
                    List<ReceiptDetailInfo> receiptDetailList = new List<ReceiptDetailInfo>();
                    if (receiptInfo.IsPalletized == "Y")
                    {
                        receiptDetailList = receiptDetailLpnDA.GetReceiptDetailLpnListByID(receiptInfo.ReceiptID, this.dataBaseID[0], this.pubParasInfo);
                    }
                    else
                    {
                        receiptDetailList = receiptDetailDA.GetReceiptDetailListByID(receiptInfo.ReceiptID, this.dataBaseID[0], this.pubParasInfo);
                    }
                    if ((receiptDetailList != null) && (receiptDetailList.Count > 0))
                    {
                        StringBuilder strXml = new StringBuilder();
                        strXml.Append("<?xml version=\"1.0\" encoding=\"utf-8\" ?> <POCheckParam> ");
                        if (string.IsNullOrEmpty(receiptInfo.ExternalReceiptID))
                        {
                            throw new Exception("入库单没有外部订单号,无法进行PO验证!");
                        }
                        strXml.Append(" <EBELN value=\"" + receiptInfo.ExternalReceiptID + "\"></EBELN> ");
                        foreach (ReceiptDetailInfo info in receiptDetailList)
                        {
                            strXml.Append(" <LineItemParam> ");
                            if (string.IsNullOrEmpty(info.ExternLineID))
                            {
                                throw new Exception("行项明细没有外部订单行号，无法进行验证!");
                            }
                            strXml.Append(" <EBELP value=\"" + info.ExternLineID + "\"></EBELP> ");
                            strXml.Append(" </LineItemParam> ");
                        }
                        strXml.Append(" </POCheckParam> ");
                        object obj = this.ExecuteMethod<IServiceHosting>("http://192.168.100.103/ServiceHosting", "POCheck", new object[] { strXml.ToString() });
                        if (obj != null)
                        {
                            string xml = obj as string;
                            XmlDocument xmlDocument = new XmlDocument();
                            xmlDocument.Load(new MemoryStream(Encoding.GetEncoding("GB2312").GetBytes(xml)));
                            XmlNodeList student = xmlDocument.DocumentElement.ChildNodes;
                            foreach (System.Xml.XmlNode node in student)
                            {
                                if (node.Name == "POCheckResult")
                                {
                                    if (node["EBELN"] == null)
                                    {
                                        throw new Exception("文档中未匹配到 EBELN");
                                    }
                                    if (receiptInfo.ExternalReceiptID != node["EBELN"].Attributes["value"].Value)
                                    {
                                        throw new Exception("检查PO信息错误");
                                    }
                                    XmlNodeList detail = node.ChildNodes;
                                    foreach (System.Xml.XmlNode detailnode in detail)
                                    {
                                        if (detailnode.Name == "LineItmeResult")
                                        {
                                            ReceiptDetailInfo receiptDetailInfo = new ReceiptDetailInfo();
                                            if (detailnode["EBELN"] == null)
                                            {
                                                throw new Exception("文档中未匹配到 EBELN");
                                            }
                                            receiptDetailInfo.ExternReceiptID = detailnode["EBELN"].Attributes["value"].Value;
                                            if (detailnode["EBELP"] == null)
                                            {
                                                throw new Exception("文档中未匹配到 EBELP");
                                            }
                                            receiptDetailInfo.ExternLineID = detailnode["EBELP"].Attributes["value"].Value;
                                            int i = 0;
                                            foreach (ReceiptDetailInfo info in receiptDetailList)
                                            {
                                                if ((receiptDetailInfo.ExternReceiptID == info.ExternReceiptID) && (receiptDetailInfo.ExternLineID == info.ExternLineID))
                                                {
                                                    receiptDetailInfo = info;
                                                    i++;
                                                }
                                            }
                                            if (i != 1)
                                            {
                                                throw new Exception("检查PO信息错误");
                                            }
                                            if (detailnode["BUKRS"] == null)
                                            {
                                                throw new Exception("文档中未匹配到 BUKRS");
                                            }
                                            if (receiptDetailInfo.OwnerID != detailnode["BUKRS"].Attributes["value"].Value)
                                            {
                                                throw new Exception("检查PO信息错误");
                                            }
                                            if (detailnode["LIFNR"] == null)
                                            {
                                                throw new Exception("文档中未匹配到 LIFNR");
                                            }
                                            if (receiptDetailInfo.VendorID != detailnode["LIFNR"].Attributes["value"].Value)
                                            {
                                                throw new Exception("检查PO信息错误");
                                            }
                                            if (detailnode["NAME1"] == null)
                                            {
                                                throw new Exception("文档中未匹配到 NAME1");
                                            }
                                            if (receiptDetailInfo.VendorName != detailnode["NAME1"].Attributes["value"].Value)
                                            {
                                                throw new Exception("检查PO信息错误");
                                            }
                                            if (detailnode["MATNR"] == null)
                                            {
                                                throw new Exception("文档中未匹配到 MATNR");
                                            }
                                            if (receiptDetailInfo.SkuID != detailnode["MATNR"].Attributes["value"].Value)
                                            {
                                                throw new Exception("检查PO信息错误");
                                            }
                                            if (detailnode["OMENG"] == null)
                                            {
                                                throw new Exception("文档中未匹配到 OMENG");
                                            }
                                            if (receiptDetailInfo.ExpectedQty != decimal.Parse(detailnode["OMENG"].Attributes["value"].Value))
                                            {
                                                throw new Exception("检查PO信息错误");
                                            }
                                            if (detailnode["PEINH"] == null)
                                            {
                                                throw new Exception("文档中未匹配到 PEINH");
                                            }
                                            if (!(receiptDetailInfo.UnitPrice == float.Parse(detailnode["PEINH"].Attributes["value"].Value)))
                                            {
                                                throw new Exception("检查PO信息错误");
                                            }
                                            if (detailnode["WAERS"] == null)
                                            {
                                                throw new Exception("文档中未匹配到 WAERS");
                                            }
                                            if (receiptDetailInfo.Udf4 != detailnode["WAERS"].Attributes["value"].Value)
                                            {
                                                throw new Exception("检查PO信息错误");
                                            }
                                            if (detailnode["WERKS"] == null)
                                            {
                                                throw new Exception("文档中未匹配到 WERKS");
                                            }
                                            if (receiptDetailInfo.Udf2 != detailnode["WERKS"].Attributes["value"].Value)
                                            {
                                                throw new Exception("检查PO信息错误");
                                            }
                                            if (detailnode["LGORT"] == null)
                                            {
                                                throw new Exception("文档中未匹配到 LGORT");
                                            }
                                            if (receiptDetailInfo.Udf3 != detailnode["LGORT"].Attributes["value"].Value)
                                            {
                                                throw new Exception("检查PO信息错误");
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
                receiptInfo.SAPAuthentication = "Y";
                result = "OK";
                receiptDA.UpdateReceipt(receiptInfo, this.dataBaseID[0]);
            }
            catch (Exception ex)
            {
                CommonErrorHandler.ErrorHandler(ex, LogType.Error);
            }
            return result;
        }

        public object ExecuteMethod<T>(string pUrl, string pMethodName, params object[] pParams)
        {
            object CS10000;
            EndpointAddress address = new EndpointAddress(pUrl);
            Binding bindinginstance = null;
            WSHttpBinding ws = new WSHttpBinding {
                MaxReceivedMessageSize = 0x1400000
            };
            ws.CloseTimeout.Add(new TimeSpan(0, 30, 0));
            ws.OpenTimeout.Add(new TimeSpan(0, 30, 0));
            ws.ReceiveTimeout.Add(new TimeSpan(10, 10, 10));
            ws.SendTimeout.Add(new TimeSpan(0, 30, 0));
            ws.AllowCookies = false;
            ws.BypassProxyOnLocal = false;
            ws.HostNameComparisonMode = HostNameComparisonMode.StrongWildcard;
            ws.MaxBufferPoolSize = 0x1f400000;
            ws.MaxReceivedMessageSize = 0x3e80000;
            ws.MessageEncoding = WSMessageEncoding.Text;
            ws.TextEncoding = Encoding.UTF8;
            ws.UseDefaultWebProxy = true;
            ws.ReaderQuotas.MaxDepth = 0x20;
            ws.ReaderQuotas.MaxStringContentLength = 0x3e80000;
            ws.ReaderQuotas.MaxArrayLength = 0x3e80000;
            ws.ReaderQuotas.MaxBytesPerRead = 0x1000;
            ws.ReaderQuotas.MaxNameTableCharCount = 0x3e80000;
            ws.Security.Transport.ClientCredentialType = HttpClientCredentialType.None;
            ws.Security.Transport.ProxyCredentialType = HttpProxyCredentialType.None;
            bindinginstance = ws;
            using (ChannelFactory<T> channel = new ChannelFactory<T>(bindinginstance, address))
            {
                T instance = channel.CreateChannel();
                IDisposable CS30002 = instance as IDisposable;
                try
                {
                    System.Type type = typeof(T);
                    return type.GetMethod(pMethodName).Invoke(instance, pParams);
                }
                catch (TimeoutException)
                {
                    (instance as ICommunicationObject).Abort();
                    throw;
                }
                catch (CommunicationException)
                {
                    (instance as ICommunicationObject).Abort();
                    throw;
                }
                catch (Exception)
                {
                    (instance as ICommunicationObject).Abort();
                    throw;
                }
                finally
                {
                    if (CS30002 != null)
                    {
                        CS30002.Dispose();
                    }
                }
            }
            return CS10000;
        }

        public string InsertOrdersByWebService(List<OrdersInfo> ordersInfoList)
        {
            EdiLogInfo edilogInfo;
            DataBase dataBase = new DataBase();
            DbConnection conn = dataBase.connection;
            conn.Open();
            DbTransaction tran = conn.BeginTransaction();
            string orderID = "OK";
            OrdersInfo ordersInfoEx = null;
            List<EdiLogInfo> edilogInfoList = new List<EdiLogInfo>();
            try
            {
                foreach (OrdersInfo info in ordersInfoList)
                {
                    string whLoginID = info.WhID;
                    info.WhID = "";
                    ordersInfoEx = info;
                    if (!ownerDA.CheckTradePartnerIDUnique(info.OwnerID, whLoginID))
                    {
                        PublicMethod.GetInstance().ShowAlertMessage("F4200_004", this.pubParasInfo.UserLanguage, new List<string> { info.OwnerID });
                    }
                    if (!string.IsNullOrEmpty(info.ConsigneeID) && !customerDA.CheckCustomerIDUnique(info.ConsigneeID, whLoginID))
                    {
                        PublicMethod.GetInstance().ShowAlertMessage("F2120_001", this.pubParasInfo.UserLanguage, new List<string> { info.ConsigneeID });
                    }
                    if (!string.IsNullOrEmpty(info.OrderID))
                    {
                        if (ordersDA.CheckOrdersIDUnique(info.OrderID, whLoginID))
                        {
                            PublicMethod.GetInstance().ShowAlertMessage("F7100_005", this.pubParasInfo.UserLanguage, new List<string> { info.OrderID });
                        }
                    }
                    else
                    {
                        info.OrderID = commonMethod.GenNextNumStr("ORDERS", whLoginID);
                    }
                    string IntransitID = string.Empty;
                    if (info.Type.ToUpper() == "TRANSFER")
                    {
                        IntransitID = commonMethod.GenNextNumStr(dataBase, tran, "INTRANSIT", this.dataBaseID[0]);
                        IntransitInfo intransitInfo = new IntransitInfo {
                            IntransitID = IntransitID,
                            SrcWhDbID = int.Parse(this.strCurrentWhName),
                            DestWhDbID = int.Parse(info.DestWhDbID),
                            OwnerID = info.OwnerID,
                            OrderID = info.OrderID,
                            ReceiptID = "",
                            OrderDate = info.OrderDate,
                            Status = "New",
                            ActualShipDate = info.ActualShipDate,
                            ExpectedReceiptDate = info.DeliveryDate,
                            IsActive = "Y",
                            CreatedBy = info.CreatedBy,
                            UpdatedBy = info.UpdatedBy,
                            CreatedDate = DateTime.Now,
                            UpdatedDate = DateTime.Now
                        };
                        IntransitDA.InsertIntransit(dataBase, tran, intransitInfo, this.dataBaseID);
                    }
                    if (!string.IsNullOrEmpty(IntransitID))
                    {
                        info.IntransitID = IntransitID;
                    }
                    ordersDA.InsertOrders(dataBase, tran, info, whLoginID);
                    if ((info.OrderDetailInfos != null) && (info.OrderDetailInfos.Count > 0))
                    {
                        foreach (OrderDetailInfo DetailInfo in info.OrderDetailInfos)
                        {
                            if (!skuDA.CheckSkuIDUnique(DetailInfo.OwnerID, DetailInfo.SkuID, whLoginID))
                            {
                                throw new Exception("货品代码" + DetailInfo.SkuID + "/货主" + DetailInfo.OwnerID + "不存在,请重新输入!");
                            }
                            if (info.Type.ToUpper() == "TRANSFER")
                            {
                                IntransitDetailInfo intransitDetailInfo = new IntransitDetailInfo {
                                    IntransitID = info.IntransitID,
                                    LineID = DetailInfo.LineID,
                                    OrderLineID = DetailInfo.LineID,
                                    ReceiptLineID = 0,
                                    OwnerID = DetailInfo.OwnerID,
                                    SkuID = DetailInfo.SkuID,
                                    UomID = DetailInfo.UomID,
                                    PackID = DetailInfo.PackID,
                                    Qty = DetailInfo.OriginalQty,
                                    ShippedQty = DetailInfo.ShippedQty,
                                    ReceivedQty = 0M,
                                    Status = IntransitStatus.New,
                                    CreatedBy = DetailInfo.CreatedBy,
                                    CreatedDate = DetailInfo.CreatedDate,
                                    UpdatedBy = DetailInfo.UpdatedBy,
                                    UpdatedDate = DetailInfo.UpdatedDate
                                };
                                IntransitDetailDA.InsertIntransitDetail(dataBase, tran, intransitDetailInfo, this.dataBaseID);
                            }
                            DetailInfo.OrderID = info.OrderID;
                            SkuInfo skuInfo = skuDA.GetSkuByID(DetailInfo.OwnerID, DetailInfo.SkuID, whLoginID);
                            DetailInfo.Length = skuInfo.Length;
                            DetailInfo.Height = skuInfo.Height;
                            DetailInfo.Width = skuInfo.Width;
                            DetailInfo.Cube = (DetailInfo.Width * DetailInfo.Height) * DetailInfo.Length;
                            DetailInfo.GrossWGT = skuInfo.GrossWgt;
                            DetailInfo.NetWGT = skuInfo.NetWgt;
                            DetailInfo.UnitPrice = float.Parse(skuInfo.CostPrice.ToString());
                            DetailInfo.ExtendedPrice = DetailInfo.UnitPrice * float.Parse(DetailInfo.OriginalQty.ToString());
                            PackInfo packInfo = packDA.GetPackByID(dataBase, tran, skuInfo.PackID, whLoginID);
                            DetailInfo.PackID = skuInfo.PackID;
                            DetailInfo.UomID = packInfo.PackUom1;
                            DetailInfo.SkuDescr = skuInfo.Descr;
                            DetailInfo.PreallocateRuleID = skuInfo.PreallocateRuleID;
                            DetailInfo.AllocateRuleID = skuInfo.AllocateRuleID;
                            DetailInfo.SkuRotation = skuInfo.RotationRuleID;
                            DetailInfo.LotAttr09 = "OK";
                            orderDetailDA.InsertOrderDetail(dataBase, tran, DetailInfo, whLoginID);
                        }
                    }
                    edilogInfo = new EdiLogInfo {
                        WhID = "",
                        LogDate = DateTime.Now,
                        IsSuccess = "成功",
                        LogDescr = "发货订单" + info.OrderID + "插入成功",
                        UserID = "CEAWebService",
                        Udf1 = "新增",
                        Udf2 = "发货订单号:" + info.OrderID,
                        Udf3 = "外部订单号" + info.ExternOrderID,
                        Udf4 = "货主名称:" + info.OwnerID
                    };
                    edilogInfoList.Add(edilogInfo);
                }
                tran.Commit();
                foreach (OrdersInfo info in ordersInfoList)
                {
                    if (info.Type.ToUpper() == "TRANSFER")
                    {
                        DbConfigBLL dbConfigBll = new DbConfigBLL();
                        DbConfigInfo dbconfigInfo = new DbConfigInfo();
                        if (info.WhID == "wh2")
                        {
                            dbconfigInfo = (DbConfigInfo) dbConfigBll.GetDbConfigByDbLoginID("wh2");
                        }
                        else
                        {
                            dbconfigInfo = (DbConfigInfo) dbConfigBll.GetDbConfigByDbLoginID("wh1");
                        }
                        if (dbconfigInfo != null)
                        {
                            this.pubParasInfo.CurrentWH = dbconfigInfo.WhDbID.ToString();
                        }
                        string result = string.Empty;
                        OutboundMgtBLL outboundMgtBLL = new OutboundMgtBLL(this.pubParasInfo);
                        result = outboundMgtBLL.AutoAllocate(info.OrderID, this.pubParasInfo.UserID);
                        info.PickDetailInfos = pickDetailDA.GetPickDetailByOrderID(info.OrderID, info.WhID + ".", this.pubParasInfo);
                        if ((info.PickDetailInfos != null) && (info.PickDetailInfos.Count > 0))
                        {
                            List<string> pickDetailID = new List<string>();
                            List<string> toLoc = new List<string>();
                            foreach (PickDetailInfo pickInfo in info.PickDetailInfos)
                            {
                                pickDetailID.Add(pickInfo.PickDetailID);
                                toLoc.Add("Pickto");
                            }
                            result = outboundMgtBLL.ConfirmPicked(pickDetailID, toLoc, this.pubParasInfo.UserID);
                            List<string> orderIDs = new List<string> {
                                info.OrderID
                            };
                            result = outboundMgtBLL.ShippedByOrderID(orderIDs, DateTime.Now.ToString(), this.pubParasInfo.UserID);
                        }
                    }
                }
                return orderID;
            }
            catch (Exception ex)
            {
                tran.Rollback();
                edilogInfoList = new List<EdiLogInfo>();
                edilogInfo = new EdiLogInfo {
                    WhID = "",
                    LogDate = DateTime.Now,
                    IsSuccess = "异常",
                    LogDescr = "发货订单" + ordersInfoEx.ReceiptID + "插入失败:" + ex.Message,
                    UserID = "CEAWebService",
                    Udf1 = "新增",
                    Udf2 = "发货订单号:" + ordersInfoEx.OrderID,
                    Udf3 = "外部订单号" + ordersInfoEx.ExternOrderID,
                    Udf4 = "货主名称:" + ordersInfoEx.OwnerID
                };
                edilogInfoList.Add(edilogInfo);
                orderID = ex.Message;
            }
            finally
            {
                edilogDA.InsertEdiLogs(edilogInfoList);
                conn.Close();
            }
            return orderID;
        }

        public string InsertReceiptByWebService(List<ReceiptInfo> receiptInfoList)
        {
            EdiLogInfo edilogInfo;
            DataBase dataBase = new DataBase();
            DbConnection conn = dataBase.connection;
            conn.Open();
            DbTransaction tran = conn.BeginTransaction();
            string receiptID = "OK";
            ReceiptInfo receiptInfoEx = null;
            List<EdiLogInfo> edilogInfoList = new List<EdiLogInfo>();
            try
            {
                foreach (ReceiptInfo info in receiptInfoList)
                {
                    string whLoginID = info.WhID + ".";
                    info.WhID = "";
                    receiptInfoEx = info;
                    if (!ownerDA.CheckTradePartnerIDUnique(info.OwnerID, whLoginID))
                    {
                        PublicMethod.GetInstance().ShowAlertMessage("F4200_004", this.pubParasInfo.UserLanguage, new List<string> { info.OwnerID });
                    }
                    if (!string.IsNullOrEmpty(info.VendorID) && !DataAccess.CreateVendorDA().CheckVendorIDUnique(dataBase, tran, info.VendorID, whLoginID))
                    {
                        PublicMethod.GetInstance().ShowAlertMessage("F4200_006", this.pubParasInfo.UserLanguage, new List<string> { info.VendorID });
                    }
                    if (!string.IsNullOrEmpty(info.ReceiptID))
                    {
                        if (receiptDA.CheckReceiptIDUnique(dataBase, tran, info.ReceiptID, whLoginID))
                        {
                            PublicMethod.GetInstance().ShowAlertMessage("F4200_007", this.pubParasInfo.UserLanguage, new List<string> { info.ReceiptID });
                        }
                        else
                        {
                            receiptID = info.ReceiptID;
                        }
                    }
                    else
                    {
                        receiptID = commonMethod.GenNextNumStr(dataBase, tran, "RECEIPT", whLoginID);
                    }
                    TradePartnerInfo owner = ownerDA.GetTradePartnerByID(dataBase, tran, info.OwnerID, whLoginID);
                    if ((owner != null) && !string.IsNullOrEmpty(owner.OwnerID))
                    {
                        if (!string.IsNullOrEmpty(owner.AsnAlphaPrefix))
                        {
                            receiptID = owner.AsnAlphaPrefix + receiptID;
                        }
                    }
                    else
                    {
                        List<string> gInitLocal6 = new List<string> {
                            info.OwnerID
                        };
                        PublicMethod.GetInstance().ShowAlertMessage("F4200_008", this.pubParasInfo.UserLanguage, gInitLocal6);
                    }
                    info.ReceiptID = receiptID;
                    receiptDA.InsertReceipt(dataBase, tran, info, whLoginID);
                    if ((info.ReceiptDetailInfos != null) && (info.ReceiptDetailInfos.Count > 0))
                    {
                        foreach (ReceiptDetailInfo DetailInfo in info.ReceiptDetailInfos)
                        {
                            if (!skuDA.CheckSkuIDUnique(DetailInfo.OwnerID, DetailInfo.SkuID, whLoginID))
                            {
                                throw new Exception("货品代码" + DetailInfo.SkuID + "/货主" + DetailInfo.OwnerID + "不存在,请重新输入!");
                            }
                            DetailInfo.ReceiptID = receiptID;
                            SkuInfo skuInfo = skuDA.GetSkuByID(DetailInfo.OwnerID, DetailInfo.SkuID, whLoginID);
                            DetailInfo.Length = skuInfo.Length;
                            DetailInfo.Height = skuInfo.Height;
                            DetailInfo.Width = skuInfo.Width;
                            DetailInfo.Cube = (DetailInfo.Width * DetailInfo.Height) * DetailInfo.Length;
                            if (DetailInfo.GrossWgt == 0f)
                            {
                                DetailInfo.GrossWgt = skuInfo.GrossWgt;
                            }
                            if (DetailInfo.NetWgt == 0f)
                            {
                                DetailInfo.NetWgt = skuInfo.NetWgt;
                            }
                            if (DetailInfo.UnitPrice == 0f)
                            {
                                DetailInfo.UnitPrice = float.Parse(skuInfo.CostPrice.ToString());
                            }
                            DetailInfo.ExtendedPrice = DetailInfo.UnitPrice * float.Parse(DetailInfo.ExpectedQty.ToString());
                            PackInfo packInfo = packDA.GetPackByID(dataBase, tran, skuInfo.PackID, whLoginID);
                            DetailInfo.PackID = skuInfo.PackID;
                            DetailInfo.UomID = packInfo.PackUom1;
                            DetailInfo.SkuDescr = skuInfo.Descr;
                            DetailInfo.ReceiptLot.LotAttr09 = "OK";
                            DetailInfo.ReceiptLot.LotAttr10 = receiptID;
                            receiptDetailDA.InsertReceiptDetail(dataBase, tran, DetailInfo, whLoginID);
                        }
                    }
                    receiptID = "OK";
                    edilogInfo = new EdiLogInfo {
                        WhID = "",
                        LogDate = DateTime.Now,
                        IsSuccess = "成功",
                        LogDescr = "入库单" + info.ReceiptID + "插入成功",
                        UserID = "CEAWebService",
                        Udf1 = "新增",
                        Udf2 = "入库单号:" + info.ReceiptID,
                        Udf3 = "外部订单号" + info.ExternalReceiptID,
                        Udf4 = "货主名称:" + info.OwnerID
                    };
                    edilogInfoList.Add(edilogInfo);
                }
                tran.Commit();
            }
            catch (Exception ex)
            {
                tran.Rollback();
                edilogInfoList = new List<EdiLogInfo>();
                edilogInfo = new EdiLogInfo {
                    WhID = "",
                    LogDate = DateTime.Now,
                    IsSuccess = "异常",
                    LogDescr = "入库单" + receiptInfoEx.ReceiptID + "插入失败:" + ex.Message,
                    UserID = "CEAWebService",
                    Udf1 = "新增",
                    Udf2 = "入库单号:" + receiptInfoEx.ReceiptID,
                    Udf3 = "外部订单号" + receiptInfoEx.ExternalReceiptID,
                    Udf4 = "货主名称:" + receiptInfoEx.OwnerID
                };
                edilogInfoList.Add(edilogInfo);
                receiptID = ex.Message;
            }
            finally
            {
                edilogDA.InsertEdiLogs(edilogInfoList);
                conn.Close();
            }
            return receiptID;
        }

        public string ReceivingPosting(List<ReceiptDetailInfo> receiptDetailInfoLists)
        {
            string whLoginID = this.dataBaseID[0];
            string result = string.Empty;
            try
            {
                if ((receiptDetailInfoLists == null) || (receiptDetailInfoLists.Count <= 0))
                {
                    return result;
                }
                StringBuilder strXml = new StringBuilder();
                strXml.Append("<?xml version=\"1.0\" encoding=\"utf-8\" ?> <ZRFCFORWMS01> ");
                ReceiptInfo receiptInfo = receiptDA.GetReceiptByID(receiptDetailInfoLists[0].ReceiptID, whLoginID, this.pubParasInfo);
                foreach (ReceiptDetailInfo info in receiptDetailInfoLists)
                {
                    strXml.Append(" <ZMM08> ");
                    strXml.Append(" <EBELN value=\"" + info.ExternReceiptID + "\"></EBELN> ");
                    strXml.Append(" <EBELP value=\"" + info.ExternLineID + "\"></EBELP> ");
                    strXml.Append(" <MATNR value=\"" + info.SkuID + "\"></MATNR> ");
                    strXml.Append(" <ERFMG value=\"" + info.ReceivedQty.ToString() + "\"></ERFMG> ");
                    strXml.Append(" <WERKS value=\"" + info.Udf2 + "\"></WERKS> ");
                    strXml.Append(" <LGORT value=\"" + info.Udf3 + "\"></LGORT> ");
                    strXml.Append(" <KZBEW value=\"B\"></KZBEW> ");
                    if ((receiptInfo != null) && (receiptInfo.ReceiptType == "Return"))
                    {
                        strXml.Append(" <BWART value=\"161\"></BWART> ");
                    }
                    else
                    {
                        strXml.Append(" <BWART value=\"101\"></BWART> ");
                    }
                    strXml.Append(" </ZMM08> ");
                }
                strXml.Append(" </ZRFCFORWMS01> ");
                object obj = this.ExecuteMethod<IServiceHosting>("http://192.168.100.106:8000/ServiceHosting", "MIGO", new object[] { strXml.ToString() });
                if (obj != null)
                {
                    string xml = obj as string;
                    XmlDocument xmlDocument = new XmlDocument();
                    xmlDocument.Load(new MemoryStream(Encoding.GetEncoding("GB2312").GetBytes(xml)));
                    XmlNodeList student = xmlDocument.DocumentElement.ChildNodes;
                    foreach (System.Xml.XmlNode node in student)
                    {
                        if (node["BWART"] == null)
                        {
                            throw new Exception("文档中未匹配到 BWART");
                        }
                        receiptInfo.Udf5 = node["BWART"].Attributes["value"].Value;
                        result = receiptInfo.Udf5;
                    }
                }
                receiptDA.UpdateReceipt(receiptInfo, whLoginID);
            }
            catch (Exception ex)
            {
                throw ex;
            }
            return result;
        }

        public string ShippingDelivery(OrdersInfo ordersInfo)
        {
            string whLoginID = this.dataBaseID[0];
            string result = string.Empty;
            try
            {
                if (ordersInfo == null)
                {
                    return result;
                }
                ordersInfo.OrderDetailInfos = orderDetailDA.GetOrderDetailListByOrderID(ordersInfo.OrderID, whLoginID, this.pubParasInfo);
                StringBuilder strXml = new StringBuilder();
                strXml.Append("<?xml version=\"1.0\" encoding=\"utf-8\" ?> <ZRFCFORWMS04> ");
                if (string.IsNullOrEmpty(ordersInfo.ExternOrderID))
                {
                    throw new Exception("发货订单没有外部订单号,无法查询发货单信息!");
                }
                strXml.Append(" <D_VBELN value=\"" + ordersInfo.ExternOrderID + "\"></D_VBELN> ");
                if ((ordersInfo.OrderDetailInfos != null) && (ordersInfo.OrderDetailInfos.Count > 0))
                {
                    strXml.Append(" <T_ITEM> ");
                    foreach (OrderDetailInfo info in ordersInfo.OrderDetailInfos)
                    {
                        strXml.Append(" <ZSD10> ");
                        strXml.Append(" <VBELN value=\"" + info.ExternOrderID + "\"></VBELN> ");
                        strXml.Append(" <POSNR value=\"" + info.ExternLineID + "\"></POSNR> ");
                        strXml.Append(" <BSTKD value=\"" + info.Udf3 + "\"></BSTKD> ");
                        strXml.Append(" <POSEX value=\"" + info.Udf1 + "\"></POSEX> ");
                        strXml.Append(" <MATNR value=\"" + info.SkuID + "\"></MATNR> ");
                        strXml.Append(" <KDMAT value=\"" + info.Udf2 + "\"></KDMAT> ");
                        strXml.Append(" <LFIMG value=\"" + info.ShippedQty.ToString() + "\"></LFIMG> ");
                        strXml.Append(" <WERKS value=\"" + info.Udf4 + "\"></WERKS> ");
                        strXml.Append(" <LGORT value=\"" + info.Udf5 + "\"></LGORT> ");
                        strXml.Append(" <KBETR value=\"" + info.Udf6 + "\"></KBETR> ");
                        strXml.Append(" <KPEIN value=\"" + info.Udf7 + "\"></KPEIN> ");
                        strXml.Append(" </ZSD10> ");
                    }
                    strXml.Append(" </T_ITEM> ");
                }
                strXml.Append(" </ZRFCFORWMS04> ");
                object obj = this.ExecuteMethod<IServiceHosting>("http://192.168.100.106:8000/ServiceHosting", "SODeliveryPost", new object[] { strXml.ToString() });
                if (obj == null)
                {
                    return result;
                }
                string xml = obj as string;
                XmlDocument xmlDocument = new XmlDocument();
                xmlDocument.Load(new MemoryStream(Encoding.GetEncoding("GB2312").GetBytes(xml)));
                XmlNodeList student = xmlDocument.DocumentElement.ChildNodes;
                foreach (System.Xml.XmlNode node in student)
                {
                    if (node["E_RETURN"] == null)
                    {
                        throw new Exception("文档中未匹配到 E_RETURN");
                    }
                    result = node["E_RETURN"].Attributes["value"].Value;
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            return result;
        }

        public List<string> SignForFeedbackInformation(DeliveryOrderInfo deliveryOrderInfo)
        {
            string whLoginID = this.dataBaseID[0];
            string result = string.Empty;
            List<string> resultList = new List<string>();
            try
            {
                object obj;
                string xml;
                XmlDocument xmlDocument;
                XmlNodeList student;
                if (deliveryOrderInfo == null)
                {
                    return resultList;
                }
                StringBuilder strXml = new StringBuilder();
                if (deliveryOrderInfo.DocType == "ORDER")
                {
                    strXml.Append("<?xml version=\"1.0\" encoding=\"utf-8\" ?> <ZRFCFORWMS05> ");
                    strXml.Append(" <SHCODE value=\"" + deliveryOrderInfo.ExternOrderId2 + "\"></SHCODE> ");
                    strXml.Append(" <VBELN value=\"" + deliveryOrderInfo.ExternOrderID + "\"></VBELN> ");
                    strXml.Append(" <SHSIGN value=\"" + deliveryOrderInfo.Udf1 + "\"></SHSIGN> ");
                    strXml.Append(" </ZRFCFORWMS05> ");
                    obj = this.ExecuteMethod<IServiceHosting>("http://192.168.100.106:8000/ServiceHosting", "SODeliverySignIn", new object[] { strXml.ToString() });
                    if (obj != null)
                    {
                        xml = obj as string;
                        xmlDocument = new XmlDocument();
                        xmlDocument.Load(new MemoryStream(Encoding.GetEncoding("GB2312").GetBytes(xml)));
                        student = xmlDocument.DocumentElement.ChildNodes;
                        foreach (System.Xml.XmlNode node in student)
                        {
                            if (node["E_RETURN"] == null)
                            {
                                throw new Exception("文档中未匹配到 E_RETURN");
                            }
                            result = node["E_RETURN"].Attributes["value"].Value;
                        }
                        resultList.Add(result);
                    }
                    return resultList;
                }
                if (!(deliveryOrderInfo.DocType == "WAVE"))
                {
                    return resultList;
                }
                List<string> orderID = new List<string>();
                if ((deliveryOrderInfo.DeliveryOrderDetailInfos == null) || (deliveryOrderInfo.DeliveryOrderDetailInfos.Count <= 0))
                {
                    return resultList;
                }
                foreach (DeliveryOrderDetailInfo info in deliveryOrderInfo.DeliveryOrderDetailInfos)
                {
                    if (!orderID.Contains(info.ExternOrderID))
                    {
                        strXml.Append("<?xml version=\"1.0\" encoding=\"utf-8\" ?> <ZRFCFORWMS05> ");
                        strXml.Append(" <SHCODE value=\"" + deliveryOrderInfo.ExternOrderId2 + "\"></SHCODE> ");
                        strXml.Append(" <VBELN value=\"" + info.ExternOrderID + "\"></VBELN> ");
                        strXml.Append(" <SHSIGN value=\"" + deliveryOrderInfo.Udf1 + "\"></SHSIGN> ");
                        strXml.Append(" </ZRFCFORWMS05> ");
                        obj = this.ExecuteMethod<IServiceHosting>("http://192.168.100.106:8000/ServiceHosting", "SODeliverySignIn", new object[] { strXml.ToString() });
                        if (obj != null)
                        {
                            xml = obj as string;
                            xmlDocument = new XmlDocument();
                            xmlDocument.Load(new MemoryStream(Encoding.GetEncoding("GB2312").GetBytes(xml)));
                            student = xmlDocument.DocumentElement.ChildNodes;
                            foreach (System.Xml.XmlNode node in student)
                            {
                                if (node["E_RETURN"] == null)
                                {
                                    throw new Exception("文档中未匹配到 E_RETURN");
                                }
                                result = node["E_RETURN"].Attributes["value"].Value;
                            }
                            resultList.Add(result);
                        }
                        orderID.Add(info.ExternOrderID);
                    }
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            return resultList;
        }

        public string SODelivery(string orderID)
        {
            string whLoginID = this.dataBaseID[0];
            string result = string.Empty;
            try
            {
                OrdersInfo ordersInfo = ordersDA.GetOrdersByID(orderID, whLoginID, this.pubParasInfo);
                if (ordersInfo == null)
                {
                    return result;
                }
                ordersInfo.OrderDetailInfos = orderDetailDA.GetOrderDetailListByOrderID(orderID, whLoginID, this.pubParasInfo);
                StringBuilder strXml = new StringBuilder();
                strXml.Append("<?xml version=\"1.0\" encoding=\"utf-8\" ?> <ZRFCFORWMS04> ");
                if (string.IsNullOrEmpty(ordersInfo.ExternOrderID))
                {
                    throw new Exception("发货订单没有外部订单号,无法查询发货单信息!");
                }
                strXml.Append(" <D_VBELN value=\"" + ordersInfo.ExternOrderID + "\"></D_VBELN> ");
                strXml.Append(" </ZRFCFORWMS04> ");
                object obj = this.ExecuteMethod<IServiceHosting>("http://192.168.100.106:8000/ServiceHosting", "SODelivery", new object[] { strXml.ToString() });
                if (obj == null)
                {
                    return result;
                }
                string xml = obj as string;
                result = "OK";
                XmlDocument xmlDocument = new XmlDocument();
                xmlDocument.Load(new MemoryStream(Encoding.GetEncoding("GB2312").GetBytes(xml)));
                XmlNodeList student = xmlDocument.DocumentElement.ChildNodes;
                foreach (System.Xml.XmlNode node in student)
                {
                    XmlNodeList detail;
                    if (node.Name == "T_HEADER")
                    {
                        detail = node.ChildNodes;
                        foreach (System.Xml.XmlNode detailnode in detail)
                        {
                            if (detailnode.Name == "ZSD09")
                            {
                                if (detailnode["BUKRS"] == null)
                                {
                                    throw new Exception("文档中未匹配到 BUKRS");
                                }
                                if (ordersInfo.OwnerID != detailnode["BUKRS"].Attributes["value"].Value)
                                {
                                    throw new Exception("反查发货订单错误");
                                }
                                if (detailnode["VBELN"] == null)
                                {
                                    throw new Exception("文档中未匹配到 VBELN");
                                }
                                if (ordersInfo.ExternOrderID != detailnode["VBELN"].Attributes["value"].Value)
                                {
                                    throw new Exception("反查发货订单错误");
                                }
                                if (detailnode["LFART"] == null)
                                {
                                    throw new Exception("文档中未匹配到 LFART");
                                }
                                if (ordersInfo.Type != detailnode["LFART"].Attributes["value"].Value)
                                {
                                    throw new Exception("反查发货订单错误");
                                }
                                if (detailnode["WAERS"] == null)
                                {
                                    throw new Exception("文档中未匹配到 WAERS");
                                }
                                if (ordersInfo.Udf1 != detailnode["WAERS"].Attributes["value"].Value)
                                {
                                    throw new Exception("反查发货订单错误");
                                }
                                if (detailnode["BILLT"] == null)
                                {
                                    throw new Exception("文档中未匹配到 BILLT");
                                }
                                if (ordersInfo.Remark != detailnode["BILLT"].Attributes["value"].Value)
                                {
                                    throw new Exception("反查发货订单错误");
                                }
                                if (detailnode["SHDATE"] == null)
                                {
                                    throw new Exception("文档中未匹配到 SHDATE");
                                }
                                if (ordersInfo.RequestedShipDate != DateTime.Parse(detailnode["SHDATE"].Attributes["value"].Value))
                                {
                                    throw new Exception("反查发货订单错误");
                                }
                            }
                        }
                    }
                    if (node.Name == "T_ITEM")
                    {
                        detail = node.ChildNodes;
                        foreach (System.Xml.XmlNode detailnode in detail)
                        {
                            if (detailnode.Name == "ZSD10")
                            {
                                OrderDetailInfo orderDetailInfo = new OrderDetailInfo();
                                if (detailnode["VBELN"] == null)
                                {
                                    throw new Exception("文档中未匹配到 VBELN");
                                }
                                orderDetailInfo.ExternOrderID = detailnode["VBELN"].Attributes["value"].Value;
                                if (detailnode["POSNR"] == null)
                                {
                                    throw new Exception("文档中未匹配到 POSNR");
                                }
                                orderDetailInfo.ExternLineID = detailnode["POSNR"].Attributes["value"].Value;
                                int i = 0;
                                foreach (OrderDetailInfo info in ordersInfo.OrderDetailInfos)
                                {
                                    if ((orderDetailInfo.ExternOrderID == info.ExternOrderID) && (orderDetailInfo.ExternLineID == info.ExternLineID))
                                    {
                                        orderDetailInfo = info;
                                        i++;
                                    }
                                }
                                if (i != 1)
                                {
                                    throw new Exception("反查发货订单错误");
                                }
                                if (detailnode["BSTKD"] == null)
                                {
                                    throw new Exception("文档中未匹配到 BSTKD");
                                }
                                if (orderDetailInfo.Udf3 != detailnode["BSTKD"].Attributes["value"].Value)
                                {
                                    throw new Exception("反查发货订单错误");
                                }
                                if (detailnode["POSEX"] == null)
                                {
                                    throw new Exception("文档中未匹配到 POSEX");
                                }
                                if (orderDetailInfo.Udf1 != detailnode["POSEX"].Attributes["value"].Value)
                                {
                                    throw new Exception("反查发货订单错误");
                                }
                                if (detailnode["MATNR"] == null)
                                {
                                    throw new Exception("文档中未匹配到 MATNR");
                                }
                                if (orderDetailInfo.SkuID != detailnode["MATNR"].Attributes["value"].Value)
                                {
                                    throw new Exception("反查发货订单错误");
                                }
                                if (detailnode["KDMAT"] == null)
                                {
                                    throw new Exception("文档中未匹配到 KDMAT");
                                }
                                if (orderDetailInfo.Udf2 != detailnode["KDMAT"].Attributes["value"].Value)
                                {
                                    throw new Exception("反查发货订单错误");
                                }
                                if (detailnode["LFIMG"] == null)
                                {
                                    throw new Exception("文档中未匹配到 LFIMG");
                                }
                                if (orderDetailInfo.PickedQty != decimal.Parse(detailnode["LFIMG"].Attributes["value"].Value))
                                {
                                    throw new Exception("反查发货订单错误");
                                }
                                if (detailnode["WERKS"] == null)
                                {
                                    throw new Exception("文档中未匹配到 WERKS");
                                }
                                if (orderDetailInfo.Udf4 != detailnode["WERKS"].Attributes["value"].Value)
                                {
                                    throw new Exception("反查发货订单错误");
                                }
                                if (detailnode["LGORT"] == null)
                                {
                                    throw new Exception("文档中未匹配到 LGORT");
                                }
                                if (orderDetailInfo.Udf5 != detailnode["LGORT"].Attributes["value"].Value)
                                {
                                    throw new Exception("反查发货订单错误");
                                }
                                if (detailnode["KBETR"] == null)
                                {
                                    throw new Exception("文档中未匹配到 KBETR");
                                }
                                if (orderDetailInfo.Udf6 != detailnode["KBETR"].Attributes["value"].Value)
                                {
                                    throw new Exception("反查发货订单错误");
                                }
                                if (detailnode["KPEIN"] == null)
                                {
                                    throw new Exception("文档中未匹配到 KPEIN");
                                }
                                if (orderDetailInfo.Udf7 != detailnode["KPEIN"].Attributes["value"].Value)
                                {
                                    throw new Exception("反查发货订单错误");
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            return result;
        }
    }
}

